package com.xudu.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.xml.transform.sax.SAXTransformerFactory;
import java.util.Base64;
import java.util.Calendar;
import java.util.Map;

/**
 * ClassName: Jwt
 * Description:
 *
 * @Author xudu
 * @Create 2024/4/9
 */
public class Jwt {

    //密钥
    private static final String SECRET = "daydayup";
    //加密算法
    private static final String ALGORITHM = "HS256";


    /**
     * 生成token
     * @param map
     * @return
     */
    public static String create(Map<String,String> map){

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,60); //设置60s后token过期


        /**
         * 创建jwt builder  Header默认
         */
        JWTCreator.Builder builder = JWT.create();

        for(String key:map.keySet()){
            builder.withClaim(key,map.get(key));
        }

        /**
         * 生成token以及指定令牌过期时间
         */
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SECRET));
        //Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return  token;

        //return null;
    }

    /**
     * 验证jwt签名
     * @param token
     * @return
     */
    public static boolean verify(String token){
        Algorithm algorithm = Algorithm.HMAC256(SECRET);

        //创建jwt验证对象
        JWTVerifier verifier = JWT.require(algorithm).build();

        try {
            verifier.verify(token);
            return true;

        }catch (JWTVerificationException e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 从token中获取用户信息
     * 获取payload为map
     * @param token
     * @return
     */
    public static Map<String,Object> getPayload(String token){
        String payload = JWT.decode(token).getPayload();
        byte[] decode = Base64.getUrlDecoder().decode(payload);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = null;
        try {
            map=objectMapper.readValue(new String(decode), Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 获取token信息方法
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

}
